<?php

namespace app\api\controller;




use app\api\model\hotel\HotelRoom;
use app\common\controller\Api;
use app\api\model\hotel\HotelCollect as HotelCollectModel;

/**
 * 酒店收藏接口
 */
class Hotelcollect extends Api
{
    protected $noNeedRight = ['*'];


    //收藏酒店
    public function add()
    {
        $hotel_id = input('hotel_id',0);

        if (empty($hotel_id))$this->error('缺少参数酒店id');

        $collect_model = new HotelCollectModel();

        $data = [
            'hotel_id'=>$hotel_id,
            'user_id'=>$this->auth->id
        ];

        $info = HotelCollectModel::where(['hotel_id'=>$hotel_id, 'user_id' => $this->auth->id])->find();
        if (empty($info)){
            $res = $collect_model->save($data);

            $this->success('收藏成功',$res);
        } else {
            $this->error('收藏失败');
        }
    }

    //删除
    public function delete()
    {
        $hotel_id = input('hotel_id',0);
        if (empty($hotel_id)) {
            $this->error('缺少参数酒店id');
        }

        $info = HotelCollectModel::where(['hotel_id'=>$hotel_id, 'user_id' => $this->auth->id])->find();

        if (!empty($info)){
            $res = $info->delete();

            $this->success('取消成功',$res);
        } else {
            $this->error('取消失败');
        }
    }

    //是否收藏
    public function iscollect()
    {
        $hotel_id = input('hotel_id',0);
        if (empty($hotel_id)) {
            $this->error('缺少参数酒店id');
        }

        $info = HotelCollectModel::where(['hotel_id'=>$hotel_id, 'user_id' => $this->auth->id])->find();

        if (!empty($info)) {
            $this->success('',1);
        } else {
            $this->success('',0);
        }
    }

    //收藏列表
    public function lists()
    {
        $lat = input('lat','');
        $lng = input('lng','');

        $list = HotelCollectModel::alias('hc')
            ->join('hotel h','hc.hotel_id = h.hotel_id')
            ->where(['hc.user_id'=>$this->auth->id])
            ->field('h.hotel_id,h.hotel_name,h.image,h.label,h.address,h.lat,h.lng')
            ->order('hc.createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);
        foreach ($list as $k => $item) {

            if ($item[ 'lng' ] && $item[ 'lat' ]&&$lng&&$lat) {
                $distance = getDistance((float) $item[ 'lng' ], (float) $item[ 'lat' ], (float) $lng, (float) $lat);
                $list[ $k ][ 'distance' ] = round($distance / 1000,1);
            } else {
                $list[ $k ][ 'distance' ] = 0;
            }

            $tickets_list = HotelRoom::where(['hotel_id'=>$item['hotel_id']])->column('price');

            $list[ $k ][ 'start_price' ] = count($tickets_list)>0?min($tickets_list):0;
        }
        $this->success('',$list);
    }

}